﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.Ctrls;
using CommunitySystem.Views;
using System.Collections.ObjectModel;
using System.Linq;

namespace CommunitySystem
{
    public partial class JinShen_DangGongWeiControl : AsyncCtrl, IReturnListenerc
	{
        private JinShengService.JinShen_MainInfo _MainInfo = null;
        private JinShengService.JinShengServiceClient _Client = null;
        private ObservableCollection<JinShengService.JinShen_DangGongWei_Detail> details = null;

        private bool CanEditInfo = true;
        private bool CanSubmit = true;
        private bool CanConfirm = false;

        public JinShen_DangGongWeiControl(JinShengService.JinShen_MainInfo mainInfo)
		{
			// 为初始化变量所必需
			InitializeComponent();
            _MainInfo = mainInfo;
            imgBtn2.IsEnabled = false;
            _Client = new JinShengService.JinShengServiceClient();

            _Client.GetOrgForHRCompleted += (sender, e) =>
            {
                if (CommunitySystem.PageView.JinShenConst.Administrator.Contains(e.Result))
                {
                    CanEditInfo = false;
                    CanSubmit = false;
                    CanConfirm = true;
                }
                if (_MainInfo.Status == CommunitySystem.PageView.JinShenConst.STATUS_Promot_Agree)
                {
                    CanEditInfo = false;
                    CanSubmit = false;
                }

                btnSubmit.IsEnabled = CanSubmit;

            };
            _Client.GetOrgForHRAsync(EHR.Common.Session.LoginUser.LoginName);

            _Client.GetJinShen_DangGongWei_DetailCompleted += (sender, e) =>
            {
                details = e.Result;
                if (details != null && details.Count > 0)//编辑
                {
                    imgBtn2.IsEnabled = true;
                    Init();
                }
                else//新增
                {
                    _Client.GetJinShen_KaoCha_DetailCompleted += (sender1, e1) =>
                    {
                        details = new ObservableCollection<JinShengService.JinShen_DangGongWei_Detail>();
                        foreach (var d in e1.Result)
                        {
                            JinShengService.JinShen_DangGongWei_Detail detail = new JinShengService.JinShen_DangGongWei_Detail()
                            {
                                EmpID = d.EmpID,
                                EmpName = d.EmpName,
                                MainID = d.MainID,
                            };
                            details.Add(detail);
                        }
                        Init();
                    };
                    _Client.GetJinShen_KaoCha_DetailAsync("MainID=" + _MainInfo.ID);
                }
            };
            _Client.GetJinShen_DangGongWei_DetailAsync("MainID=" + _MainInfo.ID);

            _Client.SaveJinShenMainInfoCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    _Client.SaveJinShen_DangGongWei_DetailAsync(details);
                }
            };
            _Client.SaveJinShen_DangGongWei_DetailCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    SilverlightMessageBoxLibrary.Message.InfoMessage("提交成功!");
                    imgBtn2.IsEnabled = true;
                }
            };
           
		}

        public void BeginReturn()
        {
            return;
        }

        private void Init()
        {
            foreach (var d in details)
            {
                Grid grid = new Grid() { Margin = new Thickness(3) };
                Border b = new Border() { BorderThickness = new Thickness(1), BorderBrush = new SolidColorBrush(Colors.Blue) ,HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch };
                Grid.SetRow(b, 0);
                Grid.SetRowSpan(b, 3);
                grid.Children.Add(b);
                grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(33, GridUnitType.Star) });
                grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(33, GridUnitType.Star) });
                grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(33, GridUnitType.Star) });
                StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal, Margin = new Thickness(3), DataContext = d, HorizontalAlignment= System.Windows.HorizontalAlignment.Stretch };
                Grid.SetRow(sp, 0);
                TextBlock tb = new TextBlock() { Text = "经党（工）委（组）", Margin = new Thickness(3) };
                sp.Children.Add(tb);
                DatePicker dp = new DatePicker();
                //if (_MainInfo.Status == CommunitySystem.PageView.JinShenConst.STATUS_Promot_Agree || CanEditInfo)
                dp.IsEnabled = CanEditInfo;
                dp.SetBinding(DatePicker.SelectedDateProperty, new System.Windows.Data.Binding("MeetingDate") 
                {
                    Mode = System.Windows.Data.BindingMode.TwoWay,
                    StringFormat = "yyyy-MM-dd" 
                });
                sp.Children.Add(dp);
                tb = new TextBlock() { Text = "日会议讨论决定如下：", Margin = new Thickness(3) };
                sp.Children.Add(tb);
                grid.Children.Add(sp);
                sp = new StackPanel() { Orientation = Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Center, Margin = new Thickness(3) };
                tb = new TextBlock() { Text = d.EmpName ,Margin = new Thickness(3)};
                DictComboBox comb = new DictComboBox() { DictCode = "IsAgree", Field = "IsAgree", DataContext = d, SelectedValuePath = "DictValue", DisplayMemberPath = "DictValue", Width = 80, Height = 23, Margin = new Thickness(5, 0, 0, 0) };
                //if (_MainInfo.Status == CommunitySystem.PageView.JinShenConst.STATUS_Promot_Agree)
                comb.IsEnabled = CanEditInfo;
                comb.SetBinding(DictComboBox.SelectedValueProperty, new System.Windows.Data.Binding("IsAgree") { Mode = System.Windows.Data.BindingMode.TwoWay });
                sp.Children.Add(tb);                
                sp.Children.Add(comb);
                tb = new TextBlock() { Text = "晋升为" + _MainInfo.Position + "(" + _MainInfo.PositionLevel + ")", Margin = new Thickness(3) };
                grid.Children.Add(sp);
                Grid.SetRow(sp, 1);

                tb = new TextBlock() { Text = "特此证明", HorizontalAlignment = System.Windows.HorizontalAlignment.Right, Margin = new Thickness(3) };
                Grid.SetRow(tb, 2);
                grid.Children.Add(tb);
                spDetails.Children.Add(grid);
            }

           
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImageButton_Click(object sender, RoutedEventArgs e)
        {
            if (Validate())
            {
                _MainInfo.Status = CommunitySystem.PageView.JinShenConst.STATUS_Party_Meeting;
                _Client.SaveJinShenMainInfoAsync(_MainInfo);
            }
        }

        private bool Validate()
        {
            var detail = details.Where(c => c.MeetingDate == null).FirstOrDefault();
            if (detail != null)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("针对" + detail.EmpName + "同志讨论会议日期不能为空!");
                return false;
            }

            detail = details.Where(c => string.IsNullOrEmpty(c.IsAgree)).FirstOrDefault();
            if (detail != null)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("请填写" + detail.EmpName + "同志讨论会议决定!");
                return false;
            }

            int count = details.Where(c => c.IsAgree == "同意").Count();
            if (count >= 2)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("最多只能有一位通知进入公示阶段!");
                return false;
            }
            return true;
        }

        /// <summary>
        /// 下一步
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void imgBtn2_Click(object sender, RoutedEventArgs e)
        {
            CommunitySystem.PageView.PublicShowControl control = new CommunitySystem.PageView.PublicShowControl(_MainInfo) { Nav = this.Nav };
            this.Nav.ShowNextPage("公示", control as AsyncCtrl);
        }
    }
}